<?php

namespace Home\Controller;

class UserController extends BaseController
{
    public function init()
    {
        $Model = new \Think\Model();
        $Model->execute("create table tpx_user (
            id integer primary key auto_increment,
            username varchar(20),
        repassword varchar(12),
        password varchar(12),
        password_salt varchar(12),
        reg_time datetime,
        reg_ip varchar(15),
        last_login_time datetime,
        last_login_ip varchar(15),
        last_change_pwd_time datetime,
        status integer 
        )");
        $this->get();
    }
    public function index()
    {
        $this->login();
    }
    public function logout() {
        session('[destroy]');
        redirect(U("User/login"),2,"您已退出登陆");
    }
	public function login() 
	{
        $uid= session('uid');
        if(!empty($uid)) {
            redirect(U("User/profile"),2,"您已登陆");
            return;
        }
        if( I('server.REQUEST_METHOD') == 'GET') {
            $this->display('login');
            return;
        }else if(I('server.REQUEST_METHOD') !='POST'){
		    redirect(U("User/login"),2,"无效的method");
            return;
        }
        $username=I('post.username');
        $password=I('post.password');
        $ip = get_client_ip();
        if( empty($username)) {
		    redirect(U("User/login"),2,"请输入用户名");
            return;
        }
        $User = D('User');
        $data=$User->where(array('username' => $username ))->find();
        if( empty($data)) {
		    redirect(U("User/login"),2,"没有找到此用户");
            return;
        }
        if( ! $User->isCorrectPassword($password)) {
		    redirect(U("User/login"),2,"密码错误，请重新输入");
            return;
        }
        $data['last_login_ip'] = $ip;
        $User->save($data);
        session('uid',$data['id']);
        session('name',$data['username']);
        session('loginip',$ip);
		redirect(U("User/profile"),2,"跳转中");

	}

	public function post() 
	{
		$User =D('User');
        if ( !$User->create()) {
            //validation not passed
            exit($User->getError());
        }
		$uid=$User->add();
        $User = M('User');
        $data=$User->find($uid);
        session('uid',$uid);
        session('name',$data['username']);
		redirect(U("User/profile"),2,"跳转中");

	}
	public function profile() 
	{
        $uid = I("uid");
        if( empty($uid)) {
            $uid= session('uid');
        }
        $User = M('User');
        if(empty($uid)) {
            redirect(U("User/login"),2,"You've not logged in yet");
            return;
        }
        $data=$User->find($uid);
        $data['cart']= \Home\Controller\CartController::get_cart_for_this_user();
//        dump($data['cart']);
        session('uid',$uid);
        $this->assign('data',$data);
		$this->display('profile');

	}
    public function signup_form() 
	{
        $this->assign('action',U("User/post"));
		$this->display('form');
	}

}
